package org.example.day07;

/**
 * 第三章节3.1.14: 方法notifyAll()唤醒所有线程
 *      注意: 唤醒的规则是倒序的,先wait的线程后被唤醒.
 */
public class MyThread12 {
    private Object lock = new Object();

    public void waitMethod() {
        try {
            synchronized (lock) {
                System.out.println("begin wait ThreadName = " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
                lock.wait(); //释放锁
                System.out.println("end wait ThreadName = " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void notifyMethod() {
        synchronized (lock) {
            System.out.println("begin notify ThreadName = " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
            lock.notifyAll();
            System.out.println("end notify ThreadName = " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread12 m12 = new MyThread12();
        for (int i = 0; i < 10; i++) {
            Thread12A ta = new Thread12A(m12);
            ta.start();
        }
        Thread.sleep(1000);
        Thread12B tb = new Thread12B(m12);
        tb.start();
    }
}

class Thread12A extends Thread{
    private MyThread12 m12;

    public Thread12A(MyThread12 m12) {
        this.m12 = m12;
    }

    @Override
    public void run() {
        m12.waitMethod();
    }
}

class Thread12B extends Thread{
    private MyThread12 m12;

    public Thread12B(MyThread12 m12) {
        this.m12 = m12;
    }

    @Override
    public void run() {
        m12.notifyMethod();
    }
}